//
//  SWFormCommonController.m
//  SWFormDemo
//
//  Created by zijin on 2018/5/28.
//  Copyright © 2018年 selwyn. All rights reserved.
//

#import "SWFormCommonController.h"
#import "SWForm.h"
#import "SWFormHandler.h"
#import "YSHYSlideViewController.h"
#import <AFNetworking.h>
#import "Header.h"
#import "HttpReq.h"
#import "XHToast.h"
#import "leftNav.h"
#import "Design.h"
#import "xianzhiViewController.h"

typedef void(^GenderSelectCompletion)(NSInteger index);

@interface SWFormCommonController ()<UIActionSheetDelegate>

@property (nonatomic, copy) GenderSelectCompletion genderSelectCompletion;
@property (nonatomic, strong) SWFormItem *age,*price;
@property (nonatomic, strong) NSArray *genders;

@end

@implementation SWFormCommonController

- (SWFormItem *)price {
    if (!_price) {
        _price = [SWFormItem new];
    }
    return _price;
}

- (SWFormItem *)age {
    if (!_age) {
        _age = [SWFormItem new];
    }
    return _age;
}

- (void)viewWillAppear:(BOOL)animated {
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(toLogin)];
    self.navigationItem.leftBarButtonItem = left;
}

- (void)toLogin {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view.window insertSubview:self.view atIndex:0];
    // Do any additional setup after loading the view.
    
    self.genders = @[@"是",@"否"];
    [self datas];
}

/**
 数据源处理
 */
- (void)datas {
    NSMutableArray *items = [NSMutableArray array];
    
    SWFormItem *name = SWFormItem_Add(@"姓名", nil, SWFormItemTypeInput, YES, YES, UIKeyboardTypeDefault);
    name.showLength = YES;
    name.info = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
    [items addObject:name];
    
    _age = SWFormItem_Add(@"订单编号", nil, SWFormItemTypeInput, YES, YES, UIKeyboardTypeNumberPad);
    _age.maxInputLength = 11;
    _age.unit = @"";
    _age.info = _model.id;
    [items addObject:_age];
    
    _price = SWFormItem_Add(@"价格", nil, SWFormItemTypeInput, YES, YES, UIKeyboardTypeNumberPad);
    _price.maxInputLength = 5;
    _price.itemUnitType = SWFormItemUnitTypeYuan;
    _price.info = _model.amout;
    [items addObject:_price];
    
    SWFormItem *gender = SWFormItem_Add(@"打印", nil, SWFormItemTypeSelect, NO, YES, UIKeyboardTypeDefault);
    gender.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectGenderWithItem:item];
    };
    if (self.taskOrPrint == 1) {
         gender.info = _model.ifPrint;
    }
    else {
        gender.info = @"否";
    }
    [items addObject:gender];
    
    SWFormItem *intro = SWFormItem_Add(@"备注", @"", SWFormItemTypeTextViewInput, YES, NO, UIKeyboardTypeDefault);
    intro.showLength = YES;
    [items addObject:intro];
    
    SWFormItem *image = SWFormItem_Add(@"附件", nil, SWFormItemTypeImage, YES, NO, UIKeyboardTypeDefault);
    image.images = @[];
    [items addObject:image];
    
    SWFormSectionItem *sectionItem = SWSectionItem(items);
    //    sectionItem.headerHeight = 10;
    //    sectionItem.footerView = [self footerView];
    //    sectionItem.footerHeight = 80;
    [self.mutableItems addObject:sectionItem];
    
    self.formTableView.tableFooterView = [self footerView];
    
    // 性别选择事件回调
    __weak typeof(self) weakSelf = self;
    self.genderSelectCompletion = ^(NSInteger index) {
        if (index!=0) {
            gender.info = weakSelf.genders[index-1];
            [weakSelf.formTableView reloadData];
        }
    };
    
    // 确定按钮点击事件回调
    self.submitCompletion = ^{
        
        NSLog(@"提交按钮点击");
        // 这里只是简单描述校验逻辑，可根据自身需求封装数据校验逻辑
        [SWFormHandler sw_checkFormNullDataWithWithDatas:weakSelf.mutableItems success:^{
            
            NSLog(@"selectImages === %@", image.selectImages);
            //NSLog(@"images === %@", image.images);
            NSLog(@"gender === %@", gender.info);
            NSLog(@"name === %@", name.info);
            
        } failure:^(NSString *error) {
            NSLog(@"error====%@",error);
        }];
    };
}

/**
 创建footer
 */
- (UIView *)footerView {
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 80)];
    
    UIButton *submitBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    submitBtn.bounds = CGRectMake(0, 0, 100, 40);
    submitBtn.center = footer.center;
    //submitBtn.backgroundColor = [UIColor purpleColor];
    [submitBtn setBackgroundImage:[UIImage imageNamed:@"but 7"] forState:UIControlStateNormal];
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:submitBtn];
    submitBtn.layer.masksToBounds = YES;
    submitBtn.layer.cornerRadius = 20;
    
    return footer;
}

- (void)selectGenderWithItem:(SWFormItem *)item{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:[NSString stringWithFormat:@"请选择%@",item.title] delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    for (int i = 0; i < self.genders.count; i++) {
        [actionSheet addButtonWithTitle:self.genders[i]];
    }
    actionSheet.tag = 10;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 10) {
        self.genderSelectCompletion(buttonIndex);
    }
}

- (void)submitAction {
    self.submitCompletion();
    if ([_model.ifPrint isEqualToString:@"是"]) {
        [XHToast showCenterWithText:@"提交成功，请前往打印"];
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.navigationController popViewControllerAnimated:YES];
        });
    }
    else {
        NSDictionary *parameters = @{@"id":_age.info, @"userId":[[NSUserDefaults standardUserDefaults]valueForKey:USERID]};
        AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
        session.responseSerializer=[AFHTTPResponseSerializer serializer];
        
        [session POST:COMPLITE parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [self compliteTask];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"失败");
        }];
    }
    
}

- (void)compliteTask {
    NSString *coin = [[NSUserDefaults standardUserDefaults]valueForKey:COIN];
    float num = coin.floatValue - _price.info.floatValue;
    NSString *coinNum = [NSString stringWithFormat:@"%.2f",num];
    NSDictionary *parameters = @{@"userId":_model.user_id,@"coin":coinNum};
    AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
    session.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    [session POST:COMPLITETASK parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        [XHToast showCenterWithText:@"提交完成"];
//        if ([_coinDelete respondsToSelector:@selector(sendValue:)]) {
//            [_coinDelete sendValue:coinNum];
//              [self.navigationController dismissViewControllerAnimated:YES completion:nil];
//              [XHToast showCenterWithText:@"提交完成"];
//        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
